/**
 *
 *
 *
 */
package ae.pcfc.etks.online.mobile.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.Principal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author nithindas.p
 *
 */
@Controller
public class TrakheesMobileController {

    DateFormat formatter;

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String initPage(ModelMap model) {
        System.out.println("inside initPage");

        return "index";
    }

    @RequestMapping(value = "/welcome/ServiceType_selection.html", method = RequestMethod.GET)
    public String serviceSelect(ModelMap model) {

        return "service_type_selection";
    }

    @RequestMapping(value = "/MobileServices_login.html", method = RequestMethod.GET)
    public String loginSelect(ModelMap model) {

        return "mobile_services_login";
    }

    @RequestMapping(value = "/welcome/FinanceServices.html", method = RequestMethod.GET)
    public String Select(ModelMap model) {

        return "finance/finance_services";
    }

    /*	@RequestMapping(value = "/login", method = RequestMethod.GET)	
     public @ResponseBody LoginResponse getLoginResponseInJSON(
     @RequestParam(value = "action") String action,
     @RequestParam(value = "username") String userName,
     @RequestParam(value = "pswrd") String password) {
     LoginResponse loginResponse = new LoginResponse();		
     if(userName.equalsIgnoreCase("mohammed") && password.equalsIgnoreCase("trakhees")) {
     loginResponse.setSessionId(00001);
     loginResponse.setMsg("Login Success");
     loginResponse.setStatus(1);
     loginResponse.setUserId(1); 
     } else {			
     loginResponse.setMsg("Login Failed");
     loginResponse.setStatus(0);			
     }		
     return loginResponse;
 
     }//
     */
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String getLoginSuccess(ModelMap model, Principal principal) {
        String name = principal.getName();
        model.addAttribute("username", name);
//		model.addAttribute("message", "Spring Security Hello World");
        return "service_category";

    }

    @RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
    public String getLoginFailed(ModelMap model) {
        model.addAttribute("message", "Invalid Login credentials.");
        return "mobile_services_login";

    }

//    @RequestMapping(value = "trakhees_web/welcome/getPrepaidBalance", method = RequestMethod.GET)
//    public @ResponseBody
//    ArrayList<PrePaidAccBalance> getPrepaidBalance(
//            @RequestParam(value = "clientId") String clientId,
//            @RequestParam(value = "clientName") String clientName,
//            @RequestParam(value = "fromDate") String fromDate,
//            @RequestParam(value = "toDate") String toDate,
//            HttpServletRequest request) {
//
//        ArrayList<Date> dates = getDatesInRange(fromDate, toDate);
//        ArrayList<PrePaidAccBalance> prePaidAccBalanceList = new ArrayList<PrePaidAccBalance>();
//        Random r = new Random();
//
//        for (int i = 0; i < dates.size(); i++) {
//            Date lDate = (Date) dates.get(i);
//            String ds = formatter.format(lDate);
////		    System.out.println(" Date is ..." + ds);
//            PrePaidAccBalance prePaidAccBalance = new PrePaidAccBalance();
//            prePaidAccBalance.setTransactionDate(ds);
//            prePaidAccBalance.setAdj(r.nextInt(500 - 100) + 100);
//            prePaidAccBalance.setPa(r.nextInt(500 - 100) + 100);
//            prePaidAccBalance.setRunningBal(r.nextInt(500 - 100) + 100);
//            prePaidAccBalance.setAmountIn(r.nextInt(1000 - 100) + 100);
//            prePaidAccBalance.setOnpeningAccBal(r.nextInt(10000 - 1000) + 1000);
//            prePaidAccBalance.setAvailableBalance(r.nextInt(10000 - 1000) + 1000);
//            prePaidAccBalanceList.add(prePaidAccBalance);
//        }
//
//        HttpSession session = request.getSession();
//        ServletContext sc = session.getServletContext();
//        String appPath = sc.getRealPath("");
//        System.out.println(appPath);
//        System.out.println();
////		buildExcelDocument(clientName, prePaidAccBalanceList, appPath);
//        return prePaidAccBalanceList;
//    }

    @RequestMapping(value = "trakhees_web/download.do", method = RequestMethod.GET)
    public void doDownload(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        final int BUFFER_SIZE = 4096;
        // get absolute path of the application
        // ServletContext context = request.getContextPath();
        // String appPath = context.getRealPath("");

        // construct the complete absolute path of the file
        HttpSession session = request.getSession();
        ServletContext sc = session.getServletContext();
        String homePath = sc.getRealPath("/");
        System.out.println(homePath);
        String fullPath = homePath + File.separator + "downloads"
                + File.separator + "BalanceSheet.xls";
        File downloadFile = new File(fullPath);
        if (downloadFile.exists()) {
            FileInputStream inputStream = new FileInputStream(downloadFile);

            // get MIME type of the file
            // String mimeType = context.getMimeType(fullPath);
            String mimeType = null;
            if (mimeType == null) {
                // set to binary type if MIME mapping not found
                mimeType = "application/octet-stream";
            }
            System.out.println("MIME type: " + mimeType);

            // set content attributes for the response
            response.setContentType(mimeType);
            response.setContentLength((int) downloadFile.length());

            // set headers for the response
            String headerKey = "Content-Disposition";
            String headerValue = String.format("attachment; filename=\"%s\"",
                    downloadFile.getName());
            response.setHeader(headerKey, headerValue);

            // get output stream of the response
            OutputStream outStream = response.getOutputStream();

            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead = -1;

            // write bytes read from the input stream into the output stream
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
                System.out.println("Inside while");
            }
            System.out.println("After while");
            outStream.flush();
            inputStream.close();
            outStream.close();
        }

    }

    private ArrayList<Date> getDatesInRange(String str_date, String end_date) {
        ArrayList<Date> dates = new ArrayList<Date>();
        /*System.out.println("str_date : " + str_date);
         System.out.println("end_date : " + end_date);
         str_date = "27/08/2010";
         end_date = "30/08/2010";*/

        formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null;
        Date endDate = null;
        try {
            startDate = (Date) formatter.parse(str_date);
            endDate = (Date) formatter.parse(end_date);
//			System.out.println("endDate : " + formatter.format(endDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        long interval = 24 * 1000 * 60 * 60; // 1 hour in millis
        long endTime = endDate.getTime(); // create your endtime here, possibly using Calendar or Date
        long curTime = startDate.getTime();
        while (curTime <= endTime) {
            dates.add(new Date(curTime));
            curTime += interval;
        }
        return dates;
    }
//	private void buildExcelDocument(String clientName,
//			ArrayList<PrePaidAccBalance> prepaidAccountBalance,
//			String homeDirectory) {
//		ArrayList<PrePaidAccBalance> balances;
//		balances = prepaidAccountBalance;
//		HSSFWorkbook workbook = new HSSFWorkbook();
//		if (balances != null && balances.size() > 0) {
//			HSSFSheet excelSheet = workbook.createSheet(clientName);
//			setExcelHeader(excelSheet, workbook);
//
//			setExcelRows(excelSheet, balances, workbook);
//
//			try {
//				File targetDir;
//
//				String fullPath = homeDirectory + File.separator + "downloads";
//				targetDir = new File(fullPath);
//				if (!targetDir.exists()) {
//					targetDir.mkdirs();
//				}
//				System.out.println(targetDir.getAbsolutePath());
//
//				File outPutFile = new File(targetDir + File.separator
//						+ "BalanceSheet.xls");
//				if (outPutFile.exists()) {
//					outPutFile.delete();
//				}
//				FileOutputStream out = new FileOutputStream(outPutFile);
//
//				workbook.write(out);
//				out.close();
//				System.out.println("Excel written successfully..");
//
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
//		}
//
//	}
//
//	public void setExcelHeader(HSSFSheet excelSheet, HSSFWorkbook wb) {
//		HSSFRow excelHeader = excelSheet.createRow(0);
//		HSSFCell cell = excelHeader.createCell(0);
//		cell.setCellValue("Sl No.");
//		cell.setCellStyle(setHeaderRowStyle(wb));
//		cell = excelHeader.createCell(1);
//		cell.setCellValue("Transaction Date");
//		cell.setCellStyle(setHeaderRowStyle(wb));
//		cell = excelHeader.createCell(2);
//		cell.setCellValue("DN#/RC#/ADJ#");
//		cell.setCellStyle(setHeaderRowStyle(wb));
//		cell = excelHeader.createCell(3);
//		cell.setCellValue("Amount in (AED)");
//		cell.setCellStyle(setHeaderRowStyle(wb));
//		cell = excelHeader.createCell(4);
//		cell.setCellValue("PA#");
//		cell.setCellStyle(setHeaderRowStyle(wb));
//		cell = excelHeader.createCell(5);
//		cell.setCellValue("Running Balance(AED)");
//		cell.setCellStyle(setHeaderRowStyle(wb));
//		
//		
////		excelHeader.createCell(0).setCellValue("Sl No.");
////		excelHeader.createCell(1).setCellValue("Transaction Date");
////		excelHeader.createCell(2).setCellValue("DN#/RC#/ADJ#");
////		excelHeader.createCell(3).setCellValue("Amount in (AED)");
////		excelHeader.createCell(4).setCellValue("PA#");
////		excelHeader.createCell(5).setCellValue("Running Balance(AED)");
//	}
//
//	public void setExcelRows(HSSFSheet excelSheet,
//			ArrayList<PrePaidAccBalance> prepaidAccountBalance, HSSFWorkbook wb) {
//		int record = 1;
//		int netAmountAed = 0;
//		int resrveAmount = 0;
//		for (PrePaidAccBalance balance : prepaidAccountBalance) {
//			HSSFRow excelRow = excelSheet.createRow(record);
//			HSSFCell cell = excelRow.createCell(0);
//			cell.setCellValue(record);
//			//cell.setCellStyle(setValueRowStyle(wb));
//			cell = excelRow.createCell(1);
//			cell.setCellValue(balance.getTransactionDate());
//			//cell.setCellStyle(setValueRowStyle(wb));
//			cell = excelRow.createCell(2);
//			cell.setCellValue(balance.getAdj());
//			//cell.setCellStyle(setValueRowStyle(wb));
//			cell = excelRow.createCell(3);
//			cell.setCellValue(balance.getAmountIn());
//			//cell.setCellStyle(setValueRowStyle(wb));
//			cell = excelRow.createCell(4);
//			cell.setCellValue(balance.getPa());
//			//cell.setCellStyle(setValueRowStyle(wb));
//			cell = excelRow.createCell(5);
//			cell.setCellValue(balance.getRunningBal());
//			//cell.setCellStyle(setValueRowStyle(wb));
//			
////			excelRow.createCell(0).setCellValue(record);
////			excelRow.createCell(1).setCellValue(balance.getTransactionDate());
////			excelRow.createCell(2).setCellValue(balance.getAdj());
////			excelRow.createCell(3).setCellValue(balance.getAmountIn());
////			excelRow.createCell(4).setCellValue(balance.getPa());
////			excelRow.createCell(5).setCellValue(balance.getRunningBal());
//			
//			netAmountAed += balance.getAmountIn();
//			resrveAmount += balance.getRunningBal();
//			record++;
//		}
//
//		int balanceSize = prepaidAccountBalance.size();
//		HSSFRow excelRow = excelSheet.createRow(record);
//		HSSFCell cell = excelRow.createCell(2);
//		cell.setCellValue("Net Amount (AED)");
//		//cell.setCellStyle(setValueRowStyle(wb));
//		cell = excelRow.createCell(3);
//		cell.setCellValue(netAmountAed);
//		//cell.setCellStyle(setValueRowStyle(wb));
//		cell = excelRow.createCell(4);
//		cell.setCellValue("Reserve Amount (AED)");
//		//cell.setCellStyle(setValueRowStyle(wb));
//		cell = excelRow.createCell(5);
//		cell.setCellValue(resrveAmount);
//		//cell.setCellStyle(setValueRowStyle(wb));
//		
//		
//		//excelRow.createCell(2).setCellValue("Net Amount (AED)");
////		excelRow.createCell(3).setCellValue(netAmountAed);
////		excelRow.createCell(4).setCellValue("Reserve Amount (AED)");
////		excelRow.createCell(5).setCellValue(resrveAmount);
//		
//		record++;
//		excelRow = excelSheet.createRow(record);
//		cell = excelRow.createCell(4);
//		cell.setCellValue("Available Balance (AED)");
//		cell.setCellStyle(setValueRowStyle(wb));
//		cell = excelRow.createCell(5);
//		cell.setCellValue(prepaidAccountBalance.get(balanceSize - 1)
//				.getAvailableBalance());
//		cell.setCellStyle(setValueRowStyle(wb));
//		
////		excelRow.createCell(4).setCellValue("Available Balance (AED)");
////		excelRow.createCell(5).setCellValue(
////				prepaidAccountBalance.get(balanceSize - 1)
////						.getAvailableBalance());
//	}
//
//	private HSSFCellStyle setValueRowStyle(HSSFWorkbook wb) {
//
//		HSSFFont font = wb.createFont();
//		font.setColor(HSSFColor.BLACK.index);
//		font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//
//		HSSFCellStyle cellStyle = wb.createCellStyle();
//		cellStyle.setFont(font);
//		cellStyle.setFillBackgroundColor(HSSFColor.AQUA.index);
//
//		return cellStyle;
//
//	}
//
//	private HSSFCellStyle setHeaderRowStyle(HSSFWorkbook wb) {
//
//		HSSFFont headerFont = wb.createFont();
//		headerFont.setColor(HSSFColor.BLUE.index);
//		headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//
//		HSSFCellStyle cellHeaderStyle = wb.createCellStyle();
//		cellHeaderStyle.setFont(headerFont);
//		cellHeaderStyle.setFillBackgroundColor(HSSFColor.AQUA.index);
//
//		return cellHeaderStyle;
//
//	}
}
